/*
 * CameraPreview.java
 * 
 * This class handles the real-time preview of the camera,
 * and handles the saving of snapshots to the 'temp' folder.
 * 
 */

package com.android.UrbanRemix;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;

// ----------------------------------------------------------------------

public class CameraPreview extends Activity implements SurfaceHolder.Callback {
	Context myContext;

	private Camera camera;

	private SurfaceView surfaceView;
	private SurfaceHolder surfaceHolder;

	private String tempFolderPath;
	private File tempFolder;

	// --------
	// on launching this activity, get the bundle that was passed to it,
	// containing
	// the path to the temporary folder.
	ImageCaptureCallback callBackObj = new ImageCaptureCallback(this);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		myContext = this;

		Bundle b = this.getIntent().getExtras();

		this.tempFolderPath = b.getString("tempFolderPath");

		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFormat(PixelFormat.TRANSLUCENT);
		setContentView(R.layout.snapshot);

		surfaceView = (SurfaceView) findViewById(R.id.surface);
		surfaceHolder = surfaceView.getHolder();
		surfaceHolder.addCallback(this);
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

		final ImageCaptureCallback jpegCallback = new ImageCaptureCallback(this);

		// ----------
		// if the user clicks on the "take snapshot" button, use the
		// jpegCallback object
		// to save the snapshot as a jpeg file. set the buttons to 'disabled',
		// and let
		// the callback object re-enable them once it has finished taking the
		// picture.

		((android.widget.Button) findViewById(R.id.takenewsnapshot))
				.setOnClickListener(new View.OnClickListener() {
					public void onClick(View view) {
						((android.widget.Button) findViewById(R.id.takenewsnapshot))
								.setVisibility(View.GONE);
						toggleButtonAvailability(false);
						camera.takePicture(null, null, jpegCallback);

					}
				});

		((android.widget.Button) findViewById(R.id.snapshotdone))
				.setOnClickListener(new View.OnClickListener() {
					public void onClick(View view) {

						finish();
					}
				});
	}

	public String getImageFileName() {
		return callBackObj.getImageFileName();
	}

	// --------
	// enable/disable the buttons; called during the saving of a picture.

	void toggleButtonAvailability(boolean b) {
		((android.widget.Button) findViewById(R.id.takenewsnapshot))
				.setEnabled(b);
		((android.widget.Button) findViewById(R.id.snapshotdone)).setEnabled(b);
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		Camera.Parameters parameters = camera.getParameters();
		parameters.setPreviewSize(width, height);
		camera.setParameters(parameters);
		camera.startPreview();
	}

	public void surfaceCreated(SurfaceHolder holder) {
		camera = Camera.open();
		try {
			camera.setPreviewDisplay(holder);
		} catch (IOException exception) {
			camera.release();
			camera = null;
		}
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		camera.stopPreview();
		camera.release();
	}

	public String getTempFolderPath() {
		return this.tempFolderPath;
	}
}

// -----------
// the ImageCaptureCallback class handles the i/o from the camera,
// and produces a .jpg file in the 'temp' folder.

class ImageCaptureCallback implements PictureCallback {
	OutputStream fileoutputStream;
	String tempFolderPath;
	CameraPreview cp;

	public static String imageFileName;

	ImageCaptureCallback(CameraPreview cp) {
		this.cp = cp;
		this.tempFolderPath = cp.getTempFolderPath();
	}

	// ----------
	// get the date/time, prefix it to "-snapshot.jpg", and
	// return the string

	public String getNewBaseFilename() {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
		String currentDateAndTime = sdf.format(cal.getTime());
		String baseFileNameAndCurrentDate = "ImageCapture-"
				+ currentDateAndTime;
		this.imageFileName = baseFileNameAndCurrentDate;
		return new String(baseFileNameAndCurrentDate + ".jpg");
	}

	public String getImageFileName() {
		return this.imageFileName;
	}

	public void onPictureTaken(byte[] data, Camera camera) {
		// --------------------------------------------------------
		// Set the name of the new snapshot file that's being saved.

		String newFilename = getNewBaseFilename();
		try {
			this.fileoutputStream = new FileOutputStream(tempFolderPath + "/"
					+ newFilename);
		} catch (FileNotFoundException e) {
			// error: filenot found
		}

		// --------------------------------------------------------
		// Write image data to the newly created, timestamped snapshot file.

		try {
			fileoutputStream.write(data);
			fileoutputStream.flush();
			fileoutputStream.close();
		} catch (Exception e) {
		}
		double keepwaiting, i, j, k;
		keepwaiting = 0;
		Request.notification(cp, "camera", "snapshot taken: " + tempFolderPath
				+ "/" + newFilename);

		cp.toggleButtonAvailability(true);

		camera.startPreview();

		cp.finish();

	}
}